package com.hanfneg.client.db;

import java.io.File;
import java.security.PublicKey;

import com.hanfeng.client.entity.Music;

import android.R.integer;
import android.app.DownloadManager.Query;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MusicDAO {
	private DBHelper dbHelper;
	private SQLiteDatabase db;
	
	public MusicDAO(Context context){
		dbHelper = new DBHelper(context);
	}
	/**
	 * 释放db对象
	 */
	public void close(){
		if (db!=null&&db.isOpen()) {
			db.close();
		}
	}
	/**
	 * 向表中插入新数据
	 * @param music
	 * @return
	 */
	public long insert(Music music){
		long rowID = -1;
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("_id", music.getId());
		values.put("musicname", music.getMusicName());
		values.put("singer", music.getSinger());
		values.put("_data", music.getUrl());
		rowID = db.insert(DBHelper.TAB_LOCALMUSIC, null, values);
		db.close();
		return rowID;
	}
	/**
	 * 更新表中数据
	 * @param music
	 * @return
	 */
	public int update(Music music){
		int count = 0;
		db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("musicname", music.getMusicName());
		values.put("singer", music.getSinger());
		count = db.update(DBHelper.TAB_LOCALMUSIC, values, "_id="+music.getId(), null);
		db.close();
		return count;		
	}
	/**
	 * 根据ID删除表中记录
	 * @param id
	 * @return
	 */
	public int delete(int id){
		int count = 0;
		db = dbHelper.getWritableDatabase();
		count = db.delete(DBHelper.TAB_LOCALMUSIC, "_id="+id, null);
		db.close();
		return count;
	}
	/**
	 * 查询表中的全部音乐记录
	 * @return
	 */
	public Cursor query(){
		Cursor cursor = null;
		db = dbHelper.getReadableDatabase();
		cursor = db.rawQuery("select * from "+DBHelper.TAB_LOCALMUSIC, null);
		return cursor;
	}
	
	/**
	 * 扫描SD卡
	 */
	public void scanSDcard(){
		//查询所有音乐
		Cursor cursor = query();
		//遍历查询结果集
		while (cursor.moveToNext()) {
			// 获取音乐ID
			int id = cursor.getInt(cursor.getColumnIndex("_id"));
			//获取音乐保存路径
			String path = cursor.getString(cursor.getColumnIndex("_data"));
			//如果音乐不存在，则从表中删除记录
			if (!(new File(path).exists())) {
				delete(id);
			}
		}
	}
}
